<template>
  <a-modal @ok="ok1" okText="确定" cancelText="取消" v-model:open="open1" title="请选择">
    请选择
    <button @click="opencreate"> 创建房间</button>
    <button @click="openroom">加入房间</button>
  </a-modal>
  <a-modal @ok="ok" okText="确定" cancelText="取消" v-model:open="open" title="请选择">
    <a-form ref="formRef" :model="formState" @onFinish="ok" :rules="rules">
      <!-- <a-form-item label="需要创建的房间号" name="name">
        <a-input v-model:value="formState.name" />
      </a-form-item> -->
      <a-form-item label="请输入你的角色" name="choose">
        <a-radio-group v-model:value="formState.choose">
          <a-radio value="A">角色A</a-radio>
          <a-radio value="B">角色B</a-radio>
        </a-radio-group>
      </a-form-item>

    </a-form>

  </a-modal>
  <a-modal @ok="ok2" okText="确定" cancelText="取消" v-model:open="open2" title="请选择">
    <a-form ref="formRef" :model="formState" @onFinish="ok" :rules="rules1">
      <a-form-item label="输入要连接的玩家id" name="name">
        <a-input v-model:value="formState.name" />
      </a-form-item>

    </a-form>

  </a-modal>
  <a-modal v-model:visible="visible" title="模块选择" :ok-button-props="{ disabled: true }"
    :cancel-button-props="{ disabled: true }">
    <router-link to="/mine">
      <p>个人中心</p>
    </router-link>
    <router-link to="/Achievements">
      <p>成就中心</p>
    </router-link>
  </a-modal>
  <img class="setting" src="@/static/set.jpg" @click="openset" alt="">
  <div class="loginview">
    <div class="stratbtn" @click="entergame(1)">
      开始今天的冒险吧
    </div>
    <div class="game5btn" @click="entergame(5)" v-if="hastell">
      游戏五限定开放！
    </div>
  </div>

</template>
<script setup>
import api from '@/api/user'
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { useAuthStore } from '@/store/index.ts'
const store = useAuthStore();
const formRef = ref();
const visible = ref(false)
const hastell = ref(0);
const daynumber = ref();
const roomid = ref();
const rules = {
  // name: [
  //   {
  //     required: true,
  //     message: '请输入你要连接的对象',
  //     trigger: 'change',
  //   },
  //   {
  //     min: 0,
  //     max: 10,
  //     message: '请输入0到10',
  //     trigger: 'blur',
  //   },
  // ],
  choose: [
    {
      required: true,
      message: '请选择你今天的角色',
      trigger: 'change',
    },
  ],
};
const rules1 = {
  name: [
    {
      required: true,
      message: '请输入你要连接的对象',
      trigger: 'change',
    },
    {
      min: 0,
      max: 10,
      message: '请输入0到10',
      trigger: 'blur',
    },
  ],
}
const formState = reactive({
  name: '',
  choose: ''
});
const openset = () => {
  visible.value = true;
}
const open = ref(false);
const open1 = ref(false);
const open2 = ref(false);
const router = useRouter();
//判断进入游戏
const entergame = (x) => {

  if (x == 5) {
    router.push("/game5")
  } {
    api.getallkey().then((res) => {
      console.log(res.data);
      let y = res.data
      let x;
      api.getkey({ keyword: store.id })
        .then((res1) => {
          x = res1[0].user1_id
          if (y[x] != null || y[x] != undefined) {
            openroom()
          } else {
            opencreate()
          }

        })
    })
  }

}
//点击确认后的回调函数
const ok = () => {
  console.log(formState);
  formRef.value
    .validate()
    .then(() => {
      api.createroom()
        .then((res) => {
          console.log(res);
          store.setroomid(String(store.id));
          api.addroom({
            key: String(store.id),
            "start": formState.choose
          }).then((res) => {
            console.log(res);
            if (formState.choose == "A") {
              router.push("/gameA")
            } else {
              router.push("/gameB")
            }

          })
        })
      // router.push("/gameA")
    })
    .catch(error => {
      console.log('error', error);
    });
}
const ok2 = () => {
  console.log(formState);
  formRef.value
    .validate()
    .then(() => {

      api.addroom({
        "key": formState.name
      }).then((res) => {
        console.log(res);
        store.setroomid(formState.name);
        api.getroom({
          key: formState.name
        }).then((res) => {
          console.log(res.data);
          if (res.data.start == "A") {
            router.push("/gameB")
          } else if (res.data.start == "B") {
            router.push("/gameA")
          } else {
            message.info("房间号不存在")
          }
        })
      })
      console.log(res);
    })
    // router.push("/gameA")

    .catch(error => {
      console.log('error', error);
    });
}
onMounted(async () => {
  store.setroomid(null);
  getinfo();
  getTellStory();
  getquestion1();

})
const getinfo = async () => {
  //生成今天题库
  api.produceProgressThisDay();
  let info = await api.getinfo()
  console.log(info);

  // if (info.msg == '未绑定账号') {
  //   router.push('mine')
  // } else
  if (!info.rows[0].selectedrole) {

    router.push({
      path: '/chooseman', query: {
        id: info.rows[0].id
      }
    })

  }
  store.setid(info.rows[0].systemuserid);
}
const getTellStory = async () => {
  const res = await api.getTellStory();
  console.log(res);
  if (res.code == 200) {
    hastell.value = 1;
  }
}
const getquestion1 = async () => {
  let res = await api.getquestion1({
    creationtime: getCurrentFormattedDate()
  })
  console.log(res.rows);
  daynumber.value = res.rows[0].daynumber;
  if (res.rows.lenth == 4) {
    hastell.value = 1;
  }

}
function getCurrentFormattedDate() {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;
}
const opencreate = () => {
  // open.value = true
  api.getkey({ keyword: store.id })
    .then((res) => {
      console.log(res[0]);
      roomid.value = res[0].user1_id;
      store.setroomid(roomid.value);
      let form = new FormData();
      form.append('key', roomid.value);
      if (res[0].user1_id == store.id) {
        if (daynumber.value % 2 == 0) {
          api.createroom(form).then((res) => {
            console.log(res);

            router.push("/gameA")


          })
        } else {
          api.createroom(form).then((res) => {
            console.log(res);

            router.push("/gameB")


          })
        }

      } else {
        if (daynumber.value % 2 == 0) {
          api.createroom(form).then((res) => {
            console.log(res);

            router.push("/gameB")


          })
        } else {
          api.createroom(form).then((res) => {
            console.log(res);
            router.push("/gameA")


          })
        }

      }
    })
}
const openroom = () => {
  // open2.value = true
  api.getkey({ keyword: store.id })
    .then((res) => {
      console.log(res[0]);
      roomid.value = res[0].user1_id;
      store.setroomid(roomid.value);
      if (res[0].user1_id == store.id) {
        if (daynumber.value % 2 == 0) {
          api.addroom({
            key: String(roomid.value),
            "start": "start"
          }).then((res) => {
            console.log(res);

            router.push("/gameA")


          })
        } else {
          api.addroom({
            key: String(roomid.value),
            "start": "start"
          }).then((res) => {
            console.log(res);

            router.push("/gameB")


          })
        }

      } else {
        if (daynumber.value % 2 == 0) {
          api.addroom({
            key: String(roomid.value),
            "start": "start"
          }).then((res) => {
            console.log(res);

            router.push("/gameB")


          })
        } else {
          api.addroom({
            key: String(roomid.value),
            "start": "start"
          }).then((res) => {
            console.log(res);
            router.push("/gameA")


          })
        }

      }
    })
}
</script>
<style lang="scss" scoped>
.setting {
  position: absolute;
  height: 4rem;
  top: 2rem;
  right: 20rem;
}

.loginview {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-image: url('@/static/back.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  gap: 2rem;


  @keyframes bigger {
    0% {
      transform: scale(1);
    }

    50% {
      transform: scale(1.2);
    }

    100% {
      transform: scale(1);
    }
  }

  @mixin tt {
    text-decoration: none;
    cursor: pointer;
  }

  .stratbtn {
    background-color: antiquewhite;
    font-size: 4rem;
    width: 20rem;
    padding: 2rem;
    border-radius: 1rem;
    @include tt;
    animation: bigger 5s linear infinite;
  }

  .game5btn {
    background-color: antiquewhite;
    font-size: 4rem;
    width: 20rem;
    padding: 2rem;
    border-radius: 1rem;
    @include tt;
  }
}
</style>